import { useWallet, useConnection } from '@solana/wallet-adapter-react';
import { useEffect, useState, useCallback } from 'react';
import { LAMPORTS_PER_SOL } from '@solana/web3.js';

export function useWalletInfo() {
  const { publicKey, connected, connecting, disconnect } = useWallet();
  const { connection } = useConnection();
  const [balance, setBalance] = useState<number | null>(null);
  const [loading, setLoading] = useState(false);
  const [network, setNetwork] = useState<string>('');
  const [mounted, setMounted] = useState(false);
  const [connectionError, setConnectionError] = useState<string | null>(null);

  // 防止水合错误
  useEffect(() => {
    setMounted(true);
  }, []);

  // 检测网络类型
  const detectNetwork = useCallback(async () => {
    if (!mounted) return;
    
    try {
      const rpcUrl = connection.rpcEndpoint;
      console.log('检测网络 RPC URL:', rpcUrl);
      
      if (rpcUrl.includes('localhost') || rpcUrl.includes('127.0.0.1')) {
        setNetwork('本地测试网');
      } else if (rpcUrl.includes('devnet')) {
        setNetwork('远程 Devnet');
      } else if (rpcUrl.includes('mainnet')) {
        setNetwork('主网');
      } else {
        setNetwork('未知网络');
      }
      
      // 测试连接是否正常
      try {
        const slot = await connection.getSlot();
        console.log('网络连接正常，当前 slot:', slot);
        setConnectionError(null);
      } catch (error) {
        console.error('网络连接测试失败:', error);
        setConnectionError(`网络连接失败: ${error instanceof Error ? error.message : '未知错误'}`);
      }
    } catch (error) {
      console.error('检测网络失败:', error);
      setNetwork('未知网络');
      setConnectionError(`网络检测失败: ${error instanceof Error ? error.message : '未知错误'}`);
    }
  }, [mounted, connection]);

  // 获取钱包余额
  const fetchBalance = useCallback(async () => {
    if (!publicKey || !connected || !mounted) {
      setBalance(null);
      return;
    }

    setLoading(true);
    try {
      const balanceInLamports = await connection.getBalance(publicKey);
      setBalance(balanceInLamports / LAMPORTS_PER_SOL);
      setConnectionError(null);
    } catch (error) {
      console.error('获取余额失败:', error);
      setBalance(null);
      setConnectionError(`获取余额失败: ${error instanceof Error ? error.message : '未知错误'}`);
    } finally {
      setLoading(false);
    }
  }, [publicKey, connected, mounted, connection]);

  useEffect(() => {
    if (mounted) {
      detectNetwork();
      fetchBalance();
    }
  }, [publicKey, connected, connection, mounted, detectNetwork, fetchBalance]);

  const formatAddress = (address: string) => {
    return `${address.slice(0, 4)}...${address.slice(-4)}`;
  };

  const formatBalance = (bal: number) => {
    return bal.toFixed(4);
  };

  return {
    publicKey,
    connected: mounted ? connected : false,
    connecting: mounted ? connecting : false,
    disconnect,
    balance,
    loading,
    network,
    connectionError,
    formatAddress,
    formatBalance,
    refreshBalance: fetchBalance,
    address: mounted && publicKey ? publicKey.toString() : '',
  };
}
